<template>
  <div>
    <div
      v-loading="loading"
      class="like-wrapper"
    >
      <div class="header">
        推荐它喜欢的商品
        <el-dropdown
          split-button
          type="primary"
          @command="handleCommand"
        >
          添加宠物用品
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              v-for="item in suppliesDict"
              :key="item.id"
              :command="item.value"
            >
              {{ item.label }}
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <div class="content">
        <div
          v-for="(item, index) in suppliesList"
          :key="item.id"
          class="supplies-list"
        >
          <div class="tool-bar">
            <div
              class="label"
              :class="{ required: item.goodsType === PET_SUPPLIES_GRAIN }"
            >
              {{ item.label }}：
            </div>
            <el-button
              type="primary"
              @click="selectGoods(index)"
            >
              选择商品
            </el-button>
            <el-button
              style="margin: 0 12px"
              @click="delAll(index)"
            >
              批量删除
            </el-button>
            <el-input-number
              v-model="item.sort"
              placeholder="请输入排序值"
              :step="1"
              step-strictly
              :min="0"
              :max="99"
              style="width: 200px"
            ></el-input-number>
            <el-button
              v-if="item.goodsType !== PET_SUPPLIES_GRAIN"
              type="text"
              size="medium"
              style="margin-left: 200px"
              @click="removeItem(index)"
            >
              删除
            </el-button>
          </div>
          <div class="copywriting">
            <span>商品动态文案：</span>
            <template v-if="item.isEditing">
              <el-input
                v-model="item.copyWritingPreffix"
                maxlength="100"
                style="width: 150px; margin-right: 12px"
                placeholder="请输入商品动态文案-前缀"
              />
              <span
                v-if="item.goodsSkuList && item.goodsSkuList.length > 0"
                class="cl-primary"
              >
                {{
                  item.isEditing
                    ? '{第一个商品}'
                    : item.goodsSkuList[0].goodsName
                }}
              </span>
              <span
                v-else
                class="cl-primary"
              >
                {第一个商品}
              </span>
              <el-input
                v-model="item.copyWritingSuffix"
                maxlength="100"
                style="width: 150px; margin-left: 12px"
                placeholder="请输入商品动态文案-后缀"
              />
            </template>
            <span
              v-else
              class="cl-primary"
            >
              {{ item.copyWritingPreffix }}
              <span
                v-if="item.goodsSkuList && item.goodsSkuList.length > 0"
                class="cl-primary"
              >
                {{
                  item.isEditing
                    ? '{第一个商品}'
                    : item.goodsSkuList[0].goodsName
                }}
              </span>
              <span
                v-else
                class="cl-primary"
              >
                {第一个商品}
              </span>
              {{ item.copyWritingSuffix }}
            </span>
            <el-button
              v-if="item.isEditing"
              type="primary"
              style="margin-left: 12px"
              @click="changeEditing(index, false)"
            >
              保存文案
            </el-button>
            <el-button
              v-else
              type="text"
              style="margin-left: 200px"
              size="medium"
              @click="changeEditing(index, true)"
            >
              编辑文案
            </el-button>
          </div>
          <div class="tips">最多可选择10件商品，下方商品拖动排序</div>
          <draggable
            v-model="item.goodsSkuList"
            class="goods-list"
            @end="changeWriting"
          >
            <div
              v-for="goodsItem in item.goodsSkuList"
              :key="goodsItem.id"
              class="goods-item"
            >
              <img
                :src="goodsItem.small"
                alt=""
              />
              <div class="name">
                <span class="txt">
                  {{ goodsItem.goodsName }}
                </span>
              </div>
            </div>
          </draggable>
          <el-empty
            v-if="item.goodsSkuList.length === 0"
            :image-size="100"
            description="暂无商品配置"
          ></el-empty>
        </div>
      </div>
      <sku-select
        ref="skuSelect"
        @selectedGoodsData="selectedGoodsData"
      ></sku-select>
    </div>
  </div>
</template>

<script>
import { remote } from '@/api/admin/dict';
import draggable from 'vuedraggable';
import { PET_SUPPLIES_GRAIN } from '@/const/type';
import SkuSelect from '@/components/qushop-dialog';
import { validatenull } from '@/util/validate';
import { addPetConfig, getPetConfig } from '@/api/shop-core/pet';
import { request } from 'qiniu-js/esm/utils';

const TEMPLATE_STR = '{goodsName}';
export default {
  name: 'likeGoods',
  components: {
    SkuSelect,
  },
  props: {
    id: {
      type: [Object, String],
    },
    value: {
      type: Boolean,
      default: false,
    },
    petIdList: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      loading: false,
      selectedIndex: 0,
      PET_SUPPLIES_GRAIN,
      suppliesDict: [],
      suppliesList: [],
      validatenull,
    };
  },
  computed: {
    visible: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit('input', val);
      },
    },
  },
  // watch: {
  //   visible(val) {
  //     if (val) {
  //       if (this.id) {
  //         this.fetchPetConfig();
  //       }
  //     }
  //   },
  // },

  async mounted() {
    await this.fetchSuppliesDict();
    if (this.id) {
      this.fetchPetConfig();
    }
  },
  methods: {
    resetGoods() {
      this.setDefaultConfig();
    },
    async fetchPetConfig() {
      const res = await getPetConfig(this.id);
      if (this.validatenull(res.data.data)) {
        this.setDefaultConfig();
        return;
      } else {
        this.suppliesList = res.data.data.map((item) => {
          const dictItem = this.suppliesDict.find(
            (dict) => dict.value === item.goodsType
          );
          console.log('dictItem', dictItem);
          return {
            ...item,
            goodsSkuList: item.skuList || [],
            label: dictItem && dictItem.label,
            copyWriting: item.copyWriting,
            copyWritingPreffix: item.copyWriting.split(TEMPLATE_STR)[0] || '',
            copyWritingSuffix: item.copyWriting.split(TEMPLATE_STR)[1] || '',
          };
        });
      }
    },
    validateForm() {
      // 校验排序值是否设置
      const emptyIndex = this.suppliesList.findIndex(
        (item) =>
          item.sort === null || item.sort === undefined || item.sort === ''
      );
      if (emptyIndex >= 0) {
        this.$message.warning(
          `请设置[${this.suppliesList[emptyIndex].label}]的排序值`
        );
        return false;
      }
      // 校验是否设置商品
      const emptyGoodsIndex = this.suppliesList.findIndex(
        (item) => item.goodsSkuList.length === 0
      );
      if (emptyGoodsIndex >= 0) {
        this.$message.warning(
          `请设置[${this.suppliesList[emptyGoodsIndex].label}]的商品`
        );
        return false;
      }
      return true;
    },
    async submit(petIdList) {
      if (this.validateForm()) {
        // 提交商品信息
        const requestBody = this.suppliesList.map((item) => {
          const requestItem = {
            petIdList,
            // petCode: info.code,
            // petNickName: info.nickName,
            goodsType: item.goodsType,
            copyWriting:
              item.copyWritingPreffix + TEMPLATE_STR + item.copyWritingSuffix,
            sort: item.sort,
            goodsSkuList: item.goodsSkuList.map((goodsItem, index) => {
              return {
                goodsId: goodsItem.goodsId,
                skuId: goodsItem.skuId,
                sort: index,
              };
            }),
          };
          if (item.id) {
            requestItem.id = item.id;
          }
          return requestItem;
        });
        try {
          this.loading = true;
          this.$emit('loading', true);
          await addPetConfig(requestBody);
          this.loading = false;
          this.$emit('loading', false);
          this.$emit('success');
        } catch (err) {
          this.loading = false;
          this.$emit('loading', false);
        }
      }
    },
    changeEditing(index, isEditing) {
      const suppliesItem = this.suppliesList[index];
      suppliesItem.isEditing = isEditing;
      if (!isEditing) {
        suppliesItem.copyWriting = `${suppliesItem.copyWritingPreffix}${TEMPLATE_STR}${suppliesItem.copyWritingSuffix}`;
      } else {
        suppliesItem.copyWritingPreffix =
          suppliesItem.copyWriting.split(TEMPLATE_STR)[0];
        suppliesItem.copyWritingSuffix =
          suppliesItem.copyWriting.split(TEMPLATE_STR)[1];
      }
      this.$set(this.suppliesList, index, suppliesItem);
    },
    delAll(index) {
      this.suppliesList[index].goodsSkuList = [];
    },
    changeWriting(index, goods) {
      if (!this.validatenull(goods)) {
        const item = this.suppliesList[index];
        this.$set(item, 'displayGoodsName', goods[0].goodsName);
      } else {
        const { suppliesList } = this;
        suppliesList.forEach((item) => {
          if (item.goodsSkuList && item.goodsSkuList.length > 0) {
            item.displayGoodsName = item.goodsSkuList[0].goodsName;
          }
        });
        this.$set(this, 'suppliesList', suppliesList);
      }
    },
    removeItem(index) {
      this.suppliesList.splice(index, 1);
    },
    selectGoods(index) {
      this.selectedIndex = index;
      this.$refs.skuSelect.open('goods');
    },
    selectedGoodsData(goods) {
      const newGoods = goods
        .map((item) => {
          item.skuId = item.id;
          return item;
        })
        .filter((item) => {
          const existItem = this.suppliesList[
            this.selectedIndex
          ].goodsSkuList.find((goodsItem) => goodsItem.skuId === item.skuId);
          return !existItem;
        });
      if (
        newGoods.length +
          this.suppliesList[this.selectedIndex].goodsSkuList.length >
        10
      ) {
        this.$message.warning('最多可选择10件商品');
        return;
      }
      const all =
        this.suppliesList[this.selectedIndex].goodsSkuList.concat(newGoods);
      this.$set(this.suppliesList[this.selectedIndex], 'goodsSkuList', all);
      this.changeWriting(this.selectedIndex, all);
    },
    handleCommand(cmd) {
      // 校验商品类型在suppliesList是否已经存在
      const existItem = this.suppliesList.find(
        (item) => item.goodsType === cmd
      );
      if (!existItem) {
        const dictItem = this.suppliesDict.find((item) => item.value === cmd);
        this.suppliesList.push({
          goodsType: dictItem.value,
          copyWriting: dictItem.description,
          copyWritingPreffix: dictItem.description.split(TEMPLATE_STR)[0] || '',
          copyWritingSuffix: dictItem.description.split(TEMPLATE_STR)[1] || '',
          label: dictItem.label,
          goodsSkuList: [],
          sort: this.suppliesList.length,
        });
      } else {
        this.$message({
          type: 'warning',
          message: `${existItem.label}已存在`,
        });
      }
    },
    async fetchSuppliesDict() {
      const { data } = await remote('pet_supplies_types');
      this.suppliesDict = data.data;
      this.setDefaultConfig();
    },
    setDefaultConfig() {
      const grain = this.suppliesDict.find(
        (item) => item.value === PET_SUPPLIES_GRAIN
      );
      this.suppliesList = [
        {
          goodsType: grain.value,
          copyWriting: grain.description,
          copyWritingPreffix: grain.description.split(TEMPLATE_STR)[0] || '',
          copyWritingSuffix: grain.description.split(TEMPLATE_STR)[1] || '',
          label: grain.label,
          sort: 0,
          goodsSkuList: [],
        },
      ];
    },
  },
};
</script>

<style lang="scss" scoped>
.like-wrapper {
  .content {
    margin-top: 12px;
    .supplies-list {
      padding: 12px 24px;
      + .supplies-list {
        border-top: 1px solid #eeeeee;
      }
    }
    .tool-bar {
      display: flex;
      align-items: center;
      margin-bottom: 12px;
      .label {
        width: 120px;
        text-align: right;
        margin-right: 12px;
        font-size: 16px;
        font-weight: 700;
        &.required {
          &::before {
            content: '*';
            color: red;
          }
        }
      }
    }
    .copywriting {
      .cl-primary {
        color: $--color-primary;
      }
    }
    .tips {
      color: #999999;
    }
    .goods-list {
      display: flex;
      flex-wrap: wrap;
      .goods-item {
        margin-top: 20px;
        text-align: center;
        margin: 20px 15px;
        img {
          width: 80px;
          height: 80px;
        }
        .name {
          margin-top: 12px;
          // 两行超出省略
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          overflow: hidden;
          text-overflow: ellipsis;
          width: 150px;
          .txt {
            display: inline-block;
            text-align: left;
          }
        }
      }
    }
  }
}
</style>
